<template>
    <div class="search-suggestion">
        <van-cell v-for="(text,index) in suggestion" @click="onsearch(text)">
            <template #title>
                <van-icon name="search"> </van-icon>
            <!-- <span>{{  text}}</span> -->
            <div v-html="highlight(text)"></div>
            </template>
        </van-cell>
    </div>
</template>

<script setup>
import {watch,reactive,ref} from 'vue'
import {getSearchSuggestions} from "../../../api/search"
import {debounce} from "lodash"
const props=defineProps({
    searchText:{
        type:  String,
    required:true
    }

})
const emits=defineEmits(["search"])
const suggestion=ref([])


 watch(()=>props.searchText,debounce((newValue,oldValue)=>{

loadSearchSuggestions(newValue)
    },1000),{
            immediate:true
        })

async function loadSearchSuggestions(newValue){
    const {data} =    await getSearchSuggestions(newValue)

    suggestion.value=data.list
}

function highlight(text){
    const hightStr=`<span style="color:red">${props.searchText}</span>`
 const reg=new RegExp(props.searchText,"gi")
 return text.replace(reg,hightStr)
}

function onsearch(text){
        emits("search",text)
}

  

</script>